#include "editor.h"

Editor::Editor(){
    _t = new Toolbox();
    load_stage(_t->stage());
    _renderImg = al_create_bitmap(DISPLAY_W, DISPLAY_H);
}

void Editor::onClick(int x, int y, int button){


    if(x < BLOCK_W * 4){

        switch(_t->onClick(x, y, button) ){
            case Toolbox::STAGE_UP:
                load_stage(_t->stage());
                break;
            case Toolbox::STAGE_DOWN:
                load_stage(_t->stage());
                break;
            case Toolbox::NEW_STAGE:
                Resources::instance()->save_stage(Resources::instance()->num_stages(),new GameBoard());
                _t->stage() = Resources::instance()->num_stages()-1;
                load_stage(_t->stage());
                break;
            case Toolbox::SAVE_STAGE:
                Resources::instance()->save_stage(_t->stage(),_gb);
                break;
        }
    }
    else{
        x = x - BLOCK_W * 4;
        int x_d = (x / BLOCK_W);
        int y_d = (y / BLOCK_H);

             if( button==1 ) _gb->_board[y_d][x_d] = _t->block();    /*Put Blocks*/
        else if( button==2 ){_gb->playerRow() = y_d;_gb->playerCol() = x_d;} /*Put Player*/
        else    _gb->_board[y_d][x_d] = new Floor();   /*Put floor*/

    }
}

ALLEGRO_BITMAP* Editor::render(){
    ALLEGRO_BITMAP* lastBmp = al_get_target_bitmap();
    al_set_target_bitmap(_renderImg);

    al_draw_bitmap(Resources::instance()->image( Resources::BACKGROUND ),0,0,0);
    al_draw_bitmap(_t->render(),0,0,0);

    al_draw_text( Resources::instance()->font(Resources::FONT_SUPER_MARIO), al_map_rgb(255,255,255), 80,0, ALLEGRO_ALIGN_CENTRE, "Super Mario");
    al_draw_text( Resources::instance()->font(Resources::FONT_SUPER_MARIO), al_map_rgb(255,255,255), 80,30, ALLEGRO_ALIGN_CENTRE, "Sokoban");
    al_draw_text( Resources::instance()->font(Resources::FONT_SUPER_MARIO), al_map_rgb(255,255,0), 80,60, ALLEGRO_ALIGN_CENTRE, "Editor");

    al_draw_bitmap(_gb->render(), DISPLAY_W - (BLOCK_W * BOARD_COLS), 0, 0);


    al_set_target_bitmap(lastBmp);
    return _renderImg;
}


void Editor::load_stage(int new_stage){
    //std::cout << "LOAD STAGE " << new_stage << std::endl;
    _gb = Resources::instance()->board(new_stage);
}
